/*
 * @(#)ExamServlet.java Time: 2013-2-28
 *
 * Copyright 2013 xuedou.com All rights reserved.
 */
package xuedou.skymoni.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import xuedou.skymoni.bean.Exam;
import xuedou.skymoni.bean.Examnum;
import xuedou.skymoni.bean.Examschool;
import xuedou.skymoni.bean.Examtime;
import xuedou.skymoni.impl.ExamImpl;
import xuedou.skymoni.service.ExamService;
import xuedou.skymoni.util.Encoding;
import xuedou.skymoni.util.StudentDelegate;

/**
 *<pre>类说明</pre>
 *<b>功能描述：</b>
 * 控制层
 * @author  jinmingming jinmingming@xuedou.com
 * @version 1.0, 2013-2-28
 */
public class ExamServlet extends HttpServlet {
	
	private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("sitecfg");
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ExamService examService = new ExamImpl();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		
		String action = request.getParameter("action");
		if(action.equalsIgnoreCase("add")){
			String sname = Encoding.codeUTF8(request.getParameter("exam.sname")).replaceAll(" ","");
			String tel = Encoding.codeUTF8(request.getParameter("exam.tel")).replaceAll(" ","");
			String school = Encoding.codeUTF8(request.getParameter("exam.school")).replaceAll(" ","");
			String issky = Encoding.codeUTF8(request.getParameter("exam.issky")).replaceAll(" ","");
			String examschool = Encoding.codeUTF8(request.getParameter("exam.examschool")).replaceAll(" ","");
//			String examtime = Encoding.codeUTF8(request.getParameter("exam.examtime")).replaceAll(" ","");
//			String examnum = Encoding.codeUTF8(request.getParameter("exam.examnum")).replaceAll(" ","");
			String examnum="布外模考";
			String ticknum = Encoding.codeUTF8(request.getParameter("exam.ticknum")).replaceAll(" ","");
			String snumber = Encoding.codeUTF8(request.getParameter("snumber")).replaceAll(" ","");//学生编号
			
			//先看是否开启了
			boolean isSky = true;
			String str = examService.isSky("issky");//是否只有蓝天学员才能报名
			if("是".equals(str)){
				isSky = StudentDelegate.isSkyStudent(snumber, sname);  //是否是蓝天学生
			}
			
			if("".equals(sname) || "".equals(tel) || "".equals(school) || "".equals(issky) || "".equals(examschool)   || "".equals(examnum) || "".equals(ticknum)){
				out.print("nosub");
			}else if("1".equals(examService.isOpen(examnum))){  //场次未开放
				out.print("error");
			}
			else if("(暂未开放)".equals(examService.isOpen(examnum)))
			{
				
				out.print("noopen");
				
			}
			else if("(已结束)".equals(examService.isOpen(examnum)))
			{
				out.print("over");
			}
			else if(!isSky){
				out.print("nosub");
			}else{
				boolean flag = examService.getStuCountBySchoolTime(examschool, null,examnum);  //验证是否人满
				if(flag){//可以报名
//					String[] schoolmsg = examService.schoolMsg(examschool);
					
//					String time = "";
//					String number = "";
//					if(("深外一模").equals(examnum)){
//						number = "一";
//						time = "3月19日";
//					}else if(("深外二模").equals(examnum)){
//						number = "二";
//						time = "4月16日";
//					}else if(("深外三模").equals(examnum)){
//						number = "三";
//						time = "5月7日";
//					}
					
//					String content = "【2013年蓝天教育深圳外国语学校龙岗分校（布外）模拟考试】 "+sname+"家长您好,您已成功报名第六届深外第"+number+"次模拟考。您的准考证号是"+ticknum+"，考试地点为蓝天教育"+examschool+"校区，考试时间是"+time+examtime+"。请保留短信于4月10日15:30至21:00凭准考证号至考试校区缴费领取“入场券”，蓝天在读学员30元/人/次，新生50元/人/次。校区地址：，校区电话：！"; // 短信内容
					String content="";
					if("否".equals(issky)){
						snumber = "";
						content = "【2013年蓝天教育深圳外国语学校龙岗分校（布外）模拟考试】 "+sname+"家长您好,欢迎您报名参加布外模拟考试。您孩子准考号为"+ticknum+"，" +
						"考试校区为"+examschool+"校区，请您5月2号之后凭准考证号至蓝天报名前台领取“入场券”。请携带100元现金作为考试押金，考完退回，如缺考将被没收。2号至5号蓝天有工作人员上班，正常工作时间为15:30分~21:00分，6号、7号蓝天教育放假。8号之后亦是正常上班时间。"; // 短信内容
					
					}
					else
					{
						content = "【2013年蓝天教育深圳外国语学校龙岗分校（布外）模拟考试】 "+sname+"家长您好,欢迎您报名参加布外模拟考试。您孩子准考号为"+ticknum+"，" +
						"考试校区为"+examschool+"校区，请您5月2号之后凭准考证号至蓝天报名前台领取“入场券”。2号至5号蓝天有工作人员上班，2号和3号的工作时间为15:30分~21:30分，4号至5号的工作时间为：9:00~21:00，6号、7号蓝天教育放假。8号之后亦是正常上班时间。"; // 短信内容
					}
					if("true".equals(bundle.getString("sendMessage"))){
						//发送短信并存储数据
						String returnmsg = examService.sendMsg(tel, content); //发送短信
//						String returnmsg="";
						if(returnmsg.length()>10 && returnmsg.length()<25){
//						if(returnmsg!=null)
//						{//提交成功
							Exam exam = new Exam();
							exam.setSname(sname);
							exam.setSchool(school);
							exam.setTel(tel);
							exam.setIssky(issky);
							exam.setExamschool(examschool);
//							exam.setExamtime(examtime);
							exam.setExamnum(examnum);
							exam.setTicknum(ticknum);
							exam.setSnumber(snumber);
							//增加考试
							boolean bn = examService.addExam(exam);
							if(bn){
								//String htmlcontent="亲爱的<em>"+sname+"</em>家长，您好。您已成功报名第六届深外第"+number+"次模拟考。您的准考证号是<em>"+ticknum+"</em>，考试地点为蓝天教育<em>"+examschool+"校区</em>，考试时间是<em>"+time+examtime+"</em>。请保留短信于<em>4月10日15:30至21:00</em>凭准考证号至考试校区缴费领取“入场券”，蓝天在读学员30元/人/次，新生50元/人/次。校区地址：<em>"+schoolmsg[0]+"</em>，校区电话：<em>"+schoolmsg[1]+"</em>！";
								String htmlcontent="";
								if("否".equals(issky))
								{
								htmlcontent="亲爱的<em>"+sname+"</em>家长您好,欢迎您报名参加布外模拟考试。您孩子准考号为<em>"+ticknum+"</em>，" +
							"考试校区为<em>"+examschool+"</em>校区，请您<em>5月2号之后</em>凭准考证号至蓝天报名前台领取“入场券”。请携带100元现金作为考试押金，考完退回，如缺考将被没收。2号至5号蓝天有工作人员上班，正常工作时间为15:30分~21:00分，6号、7号蓝天教育放假。8号之后亦是正常上班时间。"; // 短信内容
								}
								else
								{
									htmlcontent="亲爱的<em>"+sname+"</em>家长您好,欢迎您报名参加布外模拟考试。您孩子准考号为<em>"+ticknum+"</em>，" +
									"考试校区为<em>"+examschool+"</em>校区，请您<em>5月2号之后</em>凭准考证号至蓝天报名前台领取“入场券”。2号至5号蓝天有工作人员上班，正常工作时间为15:30分~21:00分，6号、7号蓝天教育放假。8号之后亦是正常上班时间。"; // 短信内容
										
								}
					
								out.print(htmlcontent);
							}else{
								out.print("nosub");
							}
							
						}else{
							//提交失败
							out.print(false);
						}
					}else{
						//测试数据
						Logger.getLogger(ExamServlet.class).debug(content);
						//只存储数据
						Exam exam = new Exam();
						exam.setSname(sname);
						exam.setSchool(school);
						exam.setTel(tel);
						exam.setIssky(issky);
						exam.setExamschool(examschool);
//						exam.setClassRoom(classRoom);
						exam.setExamnum(examnum);
						exam.setTicknum(ticknum);
						exam.setSnumber(snumber);
						examService.addExam(exam);
						out.print(content);
					}
					
				}else{
					out.print("stuFull");
				}
			}
			out.flush();
			out.close();
				
		}else if(action.equalsIgnoreCase("all")){
			//查询
			String examschool = Encoding.codeUTF8(request.getParameter("examschool"));
//			String examnum = Encoding.codeUTF8(request.getParameter("examnum"));
			String examnum="布外模考";
			List list = examService.getStuCountBySchool(examschool,examnum);
			JSONArray array = JSONArray.fromObject(list);
			out.print(array);
			out.flush();
			out.close();
		}else if(action.equals("allCount")){
			String examnum = Encoding.codeUTF8(request.getParameter("examnum"));
			String schoolname = Encoding.codeUTF8(request.getParameter("school"));
			
			int i = examService.allCount(examnum,schoolname);
			out.print(i);
			out.flush();
			out.close();
		}else if(action.equals("findByNameTelToSendMessage")){
			String sname = Encoding.codeUTF8(request.getParameter("sname")).replace(" ", "");
			String examnum = "布外模考";
			String tel = request.getParameter("tel");
			Exam exam = examService.findByNameTel(sname,tel,examnum);
			if(exam == null){
				out.print(true);  //可以报名
			}else{
				//已报名
				JSONObject obj = JSONObject.fromObject(exam);
				out.print(obj);
			}
			out.flush();
			out.close();
		}else if(action.equals("findByNameTel")){
			String sname = Encoding.codeUTF8(request.getParameter("sname")).replace(" ", "");
			String examnum = Encoding.codeUTF8(request.getParameter("examnum")).replace(" ", "");
			String snumber = Encoding.codeUTF8(request.getParameter("snumber")).replace(" ", "");
			String isornot = Encoding.codeUTF8(request.getParameter("isornot"));
			String tel = request.getParameter("tel");
						
			//先看是否开启了
			String str = examService.isSky("issky");
			boolean flag = true;
			if("是".equals(str)){
				flag = StudentDelegate.isSkyStudent(snumber, sname);  //是否是蓝天学生
			}
			
			if("是".equals(isornot)){
				flag = StudentDelegate.isSkyStudent(snumber, sname);  //是否是蓝天学生
			}
			
			if(flag){
				Exam exam = null;
				if(("否").equals(isornot)){
					snumber = "";
					exam = examService.findByNameTel(sname,tel,examnum);
				}else{
					exam = examService.findByNameTelIsSky(sname, examnum, snumber);//是否报过名
				}
				if(exam == null){
					out.print(true);  //可以报名
				}else{
					//已报名
					JSONObject obj = JSONObject.fromObject(exam);
					out.print(obj);
				}
			}else{
				out.print("notSky");
			}
			out.flush();
			out.close();
		}else if(action.equals("sendmsg")){
			
			//再次发送短信
			String msg = Encoding.codeUTF8(request.getParameter("msg"));
//			String[] schoolmsg = examService.schoolMsg(Encoding.codeUTF8(request.getParameter("examschool")));
//			String str = "校区地址："+schoolmsg[0]+"，校区电话："+schoolmsg[1]+"！";
			String content = msg ;
			
			if("true".equals(bundle.getString("sendMessage"))){
				String returnmsg = examService.sendMsg(request.getParameter("tel"), content);
//				String returnmsg="";
				if(returnmsg.length()>10 && returnmsg.length()<25){
//				if(returnmsg!=null){
					String test=request.getParameter("id");
					examService.updateSendcount(Integer.parseInt(request.getParameter("id")));
					out.print(true);
				}else{
					out.print(false);
				}
			}else{
				//测试（不发送短信）
				Logger.getLogger(ExamServlet.class).debug("不发送短信，短信内容："+content);
				examService.updateSendcount(Integer.parseInt(request.getParameter("id")));
				out.print(true);
			}
			
			out.flush();
			out.close();
		}else if(action.equals("loginexam")){
			//登陆下载
			String loginname = Encoding.codeUTF8(request.getParameter("username"));
			String loginpas = Encoding.codeUTF8(request.getParameter("password"));
			if(loginname.equals("skyedu") && loginpas.equals("sM@ky698")){
				HttpSession session = request.getSession();
				session.setAttribute("user", "yes");
				out.print(true);
			}else{
				out.print(false);
			}
			out.flush();
			out.close();
		}else if(action.equals("allExamnum")){
			//查询场次
			List<Examnum> examnumList= examService.allExamnum();
			JSONArray ar = JSONArray.fromObject(examnumList);
			out.print(ar);
			out.flush();
			out.close();
		}else if(action.equals("updateExamnum")){
			//修改场次状态
			String id = Encoding.codeUTF8(request.getParameter("id"));
			String flag = Encoding.codeUTF8(request.getParameter("flag"));
			boolean res = examService.updateExamnum(Integer.parseInt(id), flag);
			if(res){
				out.print("修改成功！");
			}else{
				out.print("修改失败！");
			}
			out.flush();
			out.close();
		}else if(action.equals("checkIssky")){
			String str = examService.isSky("issky");
			out.print(str);
			out.flush();
			out.close();
		}
		else if(action.equals("checkIsOpen"))
			{
			String temp=examService.isOpen("布外模考");
			 if("1".equals(temp)){  //场次未开放
				out.print("error");
			}
			else if("(暂未开放)".equals(temp))
			{
				
				out.print("noopen");
				
			}
			else if("(已结束)".equals(temp))
			{
				out.print("over");
			}

			out.flush();
			out.close();
			}else if(action.equals("updatecnm")){
			//修改校验
			String value = Encoding.codeUTF8(request.getParameter("value"));
			boolean res = examService.updateConfigure("issky", value);
			if(res){
				out.print("修改成功！");
			}else{
				out.print("修改失败！");
			}
			out.flush();
			out.close();
		}else if(action.equals("ispaymentlogin")){
			//登陆下载
			String loginname = Encoding.codeUTF8(request.getParameter("username"));
			String loginpas = Encoding.codeUTF8(request.getParameter("password"));
			if(loginname.equals("skyedu") && loginpas.equals("sY@ky672")){
				HttpSession session = request.getSession();
				session.setAttribute("queryuser", "yes");
				out.print(true);
			}else{
				out.print(false);
			}
			out.flush();
			out.close();
		}else if(action.equals("ispayment")){
			//查询是否交费
			String ticknum = Encoding.codeUTF8(request.getParameter("ticknum")).replace(" ", "");
			String examnum = Encoding.codeUTF8(request.getParameter("examnum")).replace(" ", "");
			Exam exam = examService.ispayment(ticknum, examnum);
			if(exam == null){
				out.print("NoResult");
			}else{
				JSONObject obj = JSONObject.fromObject(exam);
				out.print(obj);
			}
			out.flush();
			out.close();
		}else if(action.equals("updateIspayment")){
			/* 修改交费 */
			String id = Encoding.codeUTF8(request.getParameter("id")).replace(" ", "");
			String ispayment = Encoding.codeUTF8(request.getParameter("ispayment")).replace(" ", "");
			boolean flag= examService.updateIspayment(Integer.parseInt(id), ispayment);
			out.print(flag);
			out.flush();
			out.close();
		}else if(action.equals("allExamtime")){
			/* 获得所有时间段 */
			List<Examtime> ar= examService.allExamtime();
			JSONArray array = JSONArray.fromObject(ar);
			out.print(array);
			out.flush();
			out.close();
		}else if(action.equals("allExamschool")){
			/* 获得所有校区 */
			List<Examschool> ar= examService.allExamschool();
			JSONArray array = JSONArray.fromObject(ar);
			out.print(array);
			out.flush();
			out.close();
		}else if(action.equals("findClasssize")){
			/* 查询每个校区每个时间段限定人数 */
			String eschool = Encoding.codeUTF8(request.getParameter("eschool")).replace(" ", "");
			int count = examService.findClasssize(eschool);
			out.print(count);
			out.flush();
			out.close();
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	
}
